package com.ukao.pad.ui.orders;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.pad.R;
import com.ukao.pad.adapter.StoreNameTagAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.ReadBean;
import com.ukao.pad.bean.StoreInfoBean;
import com.ukao.pad.bean.UserInfoBean;
import com.ukao.pad.consts.GlobalConsts;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.OnClickPopWindowListener;
import com.ukao.pad.presenter.SelectStoresPresenter;
import com.ukao.pad.rfid.MembershipCardHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.DensityUtils;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.RegularUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.SelectStoresView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.SpinnerPopWindow;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import butterknife.OnClick;
import butterknife.Unbinder;

/**
 *下单界面
 */
public class CreateOrdersFragment extends MvpFragment<SelectStoresPresenter> implements SelectStoresView,View.OnClickListener,View.OnTouchListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

   @BindView(R.id.tv_store_title)
    TextView tvStoreTitle;
    @BindView(R.id.fragment_create_orders_tab1)
    RadioButton rbCardNo;
    @BindView(R.id.fragment_create_orders_tab2)
    RadioButton rbReadCard;
    @BindView(R.id.fragment_create_orders_tab1_layout)
    LinearLayout mTabOneLayout;
    @BindView(R.id.fragment_create_orders_tab2_layout)
    LinearLayout mTabTwoLayout;
    @BindView(R.id.create_orders_radio_group)
    RadioGroup mRadioGroup;
    @BindView(R.id.fragment_create_orders_submit)
    Button mBtnSubmit;
    @BindView(R.id.fragment_create_orders_go)
    Button  mBtnOrders;
    @BindView(R.id.top_toolbar)
    Toolbar toolbar;
    @BindView(R.id.fragment_create_orders_edit)
    ClearEditText mInputText;
    @BindView(R.id.read_error_fail)
    TextView readErrorFail;
    private  StoreInfoBean mStoreInfoBean;
    private  String storeId;
    private boolean onlyFirstShow=true;  //只第一次显示窗口
    private List<StoreInfoBean> StoreInfoList;
    private  SpinnerPopWindow  StoreListPopWindow;
    private  StoreNameTagAdapter storeNameTagAdapter;
    private  View view;
    private  String phone;
    private  boolean isNfcReadCard;
    private Handler mHandler = new Handler();
    private  boolean  isVisible;
    public CreateOrdersFragment() {

    }

    public static CreateOrdersFragment newInstance(String param1, String param2) {
        CreateOrdersFragment fragment = new CreateOrdersFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @OnClick({R.id.fragment_create_orders_go, R.id.fragment_create_orders_submit})
    public void onViewClicked(View view) {
             switch (view.getId()){
                 case R.id.fragment_create_orders_go:
                     if(!TextUtils.isEmpty(storeId)){
                         super.mvpPresenter.requestUserOrdersInfo(storeId,getText(mInputText));
                     }else {
                         T.show("请选择门店");
                     }
                     break;
                 case R.id.fragment_create_orders_submit:   //创建该账户
                     isNfcReadCard=false;
                     startForResult(CreateVipFragment.newInstance(getText(mInputText),storeId), GlobalConsts.CREATE_USER);
                     break;
             }
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }
    @Override
    protected void initView() {
        StoreListPopWindow=new SpinnerPopWindow(getActivity());
        mBtnSubmit.setVisibility(View.GONE);
    }
    @Override
    protected void initListener() {
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId){
                            case R.id.fragment_create_orders_tab1:  //切换为手机号与会员卡号
                                mTabOneLayout.setVisibility(View.VISIBLE);
                                mTabTwoLayout.setVisibility(View.GONE);
                                break;
                            case R.id.fragment_create_orders_tab2:   //读卡
                               if(TextUtils.isEmpty(storeId)){
                                   T.show("请选择门店");
                               }else {
                                   postDelayedReadCard();
                               }
                                mTabOneLayout.setVisibility(View.GONE);
                                mTabTwoLayout.setVisibility(View.VISIBLE);
                                break;
                        }
            }
        });
        mInputText.setOnEditorActionListener(mOnEditorAction);
        tvStoreTitle.setOnClickListener(this);
    }
    @Override
    protected SelectStoresPresenter createPresenter() {
        return new SelectStoresPresenter(this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_select_stores, container, false);
        unbinder=ButterKnife.bind(this,view);
        return view;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        //只第一次显示
        if(onlyFirstShow){
            onlyFirstShow=false;
            super.mvpPresenter.receiveStoreInfo();
        }
        isNfcReadCard=true;
          isVisible=true;
//        postDelayedReadCard();
    }
    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                gotoRequest();
            }
            return false;
        }
    };
    public void gotoRequest() {
        phone = getText(mInputText);
        if (phone.isEmpty()) {
            T.show("请填写手机号/会员卡号" );
            return;
        }
       hideSoftInput();
        mvpPresenter.requestUserOrdersInfo(String.valueOf(storeId),phone);
        mInputText.setText("");
    }
    /**
     * 读卡
     */
    private void postDelayedReadCard() {
        mHandler.removeCallbacksAndMessages(null);
        if (!rbReadCard.isChecked())return;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.i("读卡");
                MembershipCardHelper.getInstance().readVipCard();
            }
        }, 1500);
    }
   //不可见的时候调用
    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible=false;
        mHandler.removeCallbacksAndMessages(null);
        if(StoreListPopWindow!=null){
            //PopWindow是显示的，就关闭
            if(StoreListPopWindow.isShowing()){
                StoreListPopWindow.dismiss();
            }
        }
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {
        switch (event.getMessage()) {
            case add:/*成功*/
                if (!isVisible)return;
                String userId =(String)event.getData();
                mvpPresenter.rfidSecret(userId);
                break;
            case fali:/*读卡失败*/
                if (!isVisible)return;
                String  error=(String)event.getData();
                readErrorFail.setText(error);
                postDelayedReadCard();
                break;
            case notFound:/*没有卡*/
                if (!isVisible)return;
                postDelayedReadCard();
                break;
            case   nfc_read:  /*商米NFC读卡*/
                if (isNfcReadCard&&rbReadCard.isChecked()){
                    String  nfcUseid=(String)event.getData();
                    mvpPresenter.rfidSecret(nfcUseid);
                }
                break;
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GlobalConsts.CREATE_USER:
                    String  phone=data.getString("phone");
                    if (!CheckUtils.isEmpty(phone)){
                        mInputText.setText(phone);
                        mvpPresenter.requestUserOrdersInfo(storeId, phone);
                    }
                    break;
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        MembershipCardHelper.getInstance().onDestroy();  //取消读卡
        mHandler.removeCallbacksAndMessages(null);  //删除回调消息
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 门店列表响应成功
     */
    @Override
    public void responseStoreInfoSuccess(List<StoreInfoBean> list) {
        StoreInfoList=list;
        storeNameTagAdapter=new StoreNameTagAdapter(getActivity(),list);
        StoreListPopWindow.setAdatper(storeNameTagAdapter,0);
        StoreListPopWindow.setItemListener(clickPopWindowListener);
        StoreListPopWindow.setOnDismissListener(OnDismissListener);
        StoreListPopWindow.showAtLocation(getView(),Gravity.TOP, DensityUtils.dip2px(38),tvStoreTitle.getHeight());

        view.setBackgroundColor(Color.parseColor("#5f5f60"));
    }

    @Override
    public void responseFail(String model) {
            T.show(model);
    }

    @Override
    public void responseUserInfoSuccess(UserInfoBean model, String searchText) {
        UserInfoBean mData = model.getData();
        if (CheckUtils.isNull(mData)) {
            if (RegularUtils.isMobileSimple(searchText)){
                T.show("该手机账户不存在,请创建账户");
                mBtnSubmit.setVisibility(View.VISIBLE);
            }else{
                mBtnSubmit.setVisibility(View.GONE);
                T.show("该会员卡号不存在");
            }
        } else {  //当前页面读卡成功或者用户存在 就会跑这里的代码
            hideSoftInput();
            mBtnSubmit.setVisibility(View.GONE);
            mData.setSearchValue(searchText);
            Log.d("触发了", "responseUserInfoSuccess: ");
            start(UserInfoFragment.newInstance(String.valueOf(storeId),mData),SINGLETASK);
        }
    }
    //读卡成功
    @Override
    public void responseRfrdSuccess(ReadBean model) {
        mvpPresenter.requestUserOrdersInfo(String.valueOf(storeId),model.getData().getPhone());
    }

    private PopupWindow.OnDismissListener OnDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            view.setBackgroundColor(Color.parseColor("#F5F5F7"));
            //显示软件盘
            showSoftInput(mInputText);
        }
    };

    /**
     *门店窗口选择点击事件
     */
    private  OnClickPopWindowListener clickPopWindowListener=new OnClickPopWindowListener() {
        @Override
        public void onSureItemClick(Object message) {
            mStoreInfoBean = (StoreInfoBean) message;
            storeId=mStoreInfoBean.getId()+"";
            tvStoreTitle.setText(mStoreInfoBean.getName());
            StoreListPopWindow.dismiss();
        }
    };

    @Override
    public void onClick(View v) {
            switch (v.getId()){
                case R.id.tv_store_title: //选择门店
                       hideSoftInput();
                        if(StoreInfoList!=null){
                            StoreListPopWindow.showAtLocation(getView(),Gravity.TOP, DensityUtils.dip2px(38),tvStoreTitle.getHeight());
                            view.setBackgroundColor(Color.parseColor("#5f5f60"));
                        }else {
                            super.mvpPresenter.receiveStoreInfo();
                        }
                    break;
            }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

}
